import {Restivus} from 'meteor/nimble:restivus';
import {Meteor} from 'meteor/meteor';
import { Random } from 'meteor/random';
import {Gateways} from '../imports/api/gateways';
import {lockProjects} from '../imports/api/lock_projects';
// const mqttUrl = '119.254.97.31';
const mqttUrl = 'nodeapis.miitzc.com';
// const mqttUrl = '192.168.89.35';
import {LockFingerprints} from '../imports/api/lock_fingerprints';
if (Meteor.isServer) {
    Meteor.startup(() => {
        let Api = new Restivus({
            useDefaultAuth: true,
            prettyJson: true,
        });
        // 添加指纹
        Api.addRoute('addFinger', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const deviceId = param.deviceId;
                        const productNumber = param.productNumber;
                        const gatewayId = param.gatewayId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            try {
                                const result = HTTP.call('POST', `http://${mqttUrl}/addFingerprint`, {
                                    data: { productNumber: productNumber, devID: deviceId, gatewayId: gatewayId}
                                });
                                const content = JSON.parse(result.content);
                                if (content.success === true) {
                                    return  {success: true, result: '指纹添加成功!', resultCode: 1000};
                                }else{
                                    return  {success: false, result: '指纹添加失败！', resultCode: 1004};
                                }
                            } catch (e) {
                                return  {success: false, result: '指纹添加失败！', resultCode: 1004};
                            }

                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到登录用户的信息！', resultCode: 1002};
                }
            }
        });
        /*// 添加一次性锁密码
         Api.addRoute('addOneLockPwd', {authRequired: false}, {
         post: {
         action() {
         if (this.bodyParams) {
         const param = this.bodyParams;
         const logintoken = param.token;
         const deviceId = param.deviceId;
         const pwd = param.password;
         const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
         if(user) {
         delete param.token;
         const lps = LockPasswords.find({deviceId: deviceId},{limit: 1, sort: {row: -1}}).fetch();
         if(lps.length > 0){
         param['row'] = parseInt(lps[0].row) + 1 ;
         }else{
         param['row'] = 1;
         }
         param['create_uid'] = user._id;
         param['create_uname'] = user.username;
         const lp = LockPasswords.insert(param);
         const gateways = Gateways.findOne({'devices.d_id': deviceId});
         if(lp && gateways){
         console.log('deviceId : ', deviceId);
         console.log('data : ', pwd);
         try {
         HTTP.call('GET', `http://${mqttUrl}/getOnePwdMessage`, {
         data: { deviceId: deviceId, gatewayId: gateways.devId, data: pwd},
         headers: {
         "content-type":"application/json",
         "Accept":"application/json"
         },
         }, function (error, result) {
         if (!error) {
         return  {success: true, result: '锁密码同步请求成功!', resultCode: 1000};
         }else{
         return  {success: false, result: '锁密码同步请求失败！', resultCode: 1004};
         }
         });
         return true;
         } catch (e) {
         // Got a network error, timeout, or HTTP error in the 400 or 500 range.
         return false;
         }
         return {success: true,result: '锁密码添加成功！', resultCode: 1000};

         }else{
         return {success: false, result: '锁密码添加失败！', resultCode: 1004};
         }
         }else{
         return {success: false, result: '请登录！', resultCode: 1004};
         }
         }
         return {success: false, result: '没有获取到登录用户的信息！', resultCode: 1002};
         }
         }
         });*/
        // 添加一次性指纹
        Api.addRoute('addOneFinger', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const deviceId = param.deviceId;
                        const productNumber = param.productNumber;
                        const gatewayId = param.gatewayId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        const times = param.times;
                        const endTime = param.endTime;
                        if(user) {
                            try {
                                const result = HTTP.call('POST', `http://${mqttUrl}/addOneFingerprint`, {
                                    data: { productNumber: productNumber, devID: deviceId, gatewayId: gatewayId, times: times, duration: endTime}
                                });
                                const content = JSON.parse(result.content);
                                if (content.success === true) {
                                    return  {success: true, result: '一次性指纹添加成功!', resultCode: 1000};
                                }else{
                                    return  {success: false, result: '一次性指纹添加失败！', resultCode: 1004};
                                }
                            } catch (e) {
                                return  {success: false, result: '一次性指纹添加失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到登录用户的信息！', resultCode: 1002};
                }
            }
        });
        // 添加卡片
        Api.addRoute('addDeviceCard', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const deviceId = param.deviceId;
                        const productNumber = param.productNumber;
                        const gatewayId = param.gatewayId;
                        const cardId = param.cardId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            try {
                                const result = HTTP.call('POST', `http://${mqttUrl}/addCard`, {
                                    data: { productNumber: productNumber, devID: deviceId, gatewayId: gatewayId, cardId: cardId}
                                });
                                const content = JSON.parse(result.content);
                                if (content.success === true) {
                                    return  {success: true, result: '卡片添加成功!', resultCode: 1000};
                                }else{
                                    return  {success: false, result: '卡片添加失败！', resultCode: 1004};
                                }
                            } catch (e) {
                                return  {success: false, result: '卡片添加失败！', resultCode: 1004};
                            }

                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到登录用户的信息！', resultCode: 1002};
                }
            }
        });
        /*// 添加一次性锁密码
         Api.addRoute('addOneLockPwd', {authRequired: false}, {
         post: {
         action() {
         if (this.bodyParams) {
         const param = this.bodyParams;
         const logintoken = param.token;
         const deviceId = param.deviceId;
         const pwd = param.password;
         const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
         if(user) {
         delete param.token;
         const lps = LockPasswords.find({deviceId: deviceId},{limit: 1, sort: {row: -1}}).fetch();
         if(lps.length > 0){
         param['row'] = parseInt(lps[0].row) + 1 ;
         }else{
         param['row'] = 1;
         }
         param['create_uid'] = user._id;
         param['create_uname'] = user.username;
         const lp = LockPasswords.insert(param);
         const gateways = Gateways.findOne({'devices.d_id': deviceId});
         if(lp && gateways){
         console.log('deviceId : ', deviceId);
         console.log('data : ', pwd);
         try {
         HTTP.call('GET', `http://${mqttUrl}/getOnePwdMessage`, {
         data: { deviceId: deviceId, gatewayId: gateways.devId, data: pwd},
         headers: {
         "content-type":"application/json",
         "Accept":"application/json"
         },
         }, function (error, result) {
         if (!error) {
         return  {success: true, result: '锁密码同步请求成功!', resultCode: 1000};
         }else{
         return  {success: false, result: '锁密码同步请求失败！', resultCode: 1004};
         }
         });
         return true;
         } catch (e) {
         // Got a network error, timeout, or HTTP error in the 400 or 500 range.
         return false;
         }
         return {success: true,result: '锁密码添加成功！', resultCode: 1000};

         }else{
         return {success: false, result: '锁密码添加失败！', resultCode: 1004};
         }
         }else{
         return {success: false, result: '请登录！', resultCode: 1004};
         }
         }
         return {success: false, result: '没有获取到登录用户的信息！', resultCode: 1002};
         }
         }
         });*/
        // 添加一次性卡片
        Api.addRoute('addOneDeviceCard', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const deviceId = param.deviceId;
                        const productNumber = param.productNumber;
                        const gatewayId = param.gatewayId;
                        const cardId = param.cardId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        const startTime = param.startTime;
                        const endTime = param.endTime;
                        const times = param.times;
                        if(user) {
                            try {
                                const result = HTTP.call('POST', `https://smart.miitzc.com/tmall/appSetOnceCard`, {
                                    data: { productNumber: productNumber, devID: deviceId, gatewayId: gatewayId, cardId: cardId, startTime: startTime, endTime: endTime, times: times}
                                });
                                const content = JSON.parse(result.content);
                                if (content.success === true) {
                                    return  {success: true, result: '一次性卡片添加成功!', resultCode: 1000};
                                }else{
                                    return  {success: false, result: '一次性卡片添加失败！', resultCode: 1004};
                                }
                            } catch (e) {
                                return  {success: false, result: '一次性卡片添加失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到登录用户的信息！', resultCode: 1002};
                }
            }
        });
        //获取锁的指纹信息
        Api.addRoute('getFingersByDeviceId', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const deviceId = param.deviceId;
                        const type = param.type;
                        console.log('deviceId : ', deviceId);
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken},{fields: { fingerprints: 1}});
                        if(user) {
                            const fingers = lockProjects.find({deviceId: deviceId, type: type}).fetch();
                            console.log('fingers : ', fingers);
                            return {success: true, resultCode: 1000, result: fingers};
                        }else{
                            return {success: false, result: [], resultCode: 1004};
                        }
                    }
                    // return {success: false, result: '请求出现问题！', resultCode: 1002};
                }
            }
        });
        //删除项目信息
        Api.addRoute('deleteLockProject', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const productNumber = param.productNumber;
                        const devID = param.deviceId;
                        const index = param.index;
                        const gatewayId = param.gatewayId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken},{fields: { fingerprints: 1}});
                        if(user) {
                            try {
                                const result = HTTP.call('POST', `http://${mqttUrl}/delLockProject`, {
                                    data: { productNumber: productNumber, devID: devID, gatewayId: gatewayId, index: index}
                                });
                                const content = JSON.parse(result.content);
                                if (content.success === true) {
                                    return  {success: true, result: '删除成功!', resultCode: 1000};
                                }else{
                                    return  {success: false, result: '删除失败！', resultCode: 1004};
                                }
                            } catch (e) {
                                return  {success: false, result: '删除失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    // return {success: false, result: '请求出现问题！', resultCode: 1002};
                }
            }
        });
        // 修改lock_projects中的name
        Api.addRoute('updateLockProject', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const index = param.index;
                    const deviceId = param.deviceId;
                    const name = param.name;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    console.log('param : ', param);
                    if(user) {
                        const lp = lockProjects.update({deviceId: deviceId, index: parseInt(index)}, {$set: {name: name}});
                        console.log('lp : ', lp);
                        if(lp){
                            return {success: true, result: '项目名称修改成功！', resultCode: 1000}
                        }else{
                            return {success: false, result: '项目名称修改失败！', resultCode: 1004}
                        }

                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
    });

}